<template>
  <CommonPage show-footer>
    <div class="w-full f-c-c">
      <div class="max-w-900 w-full">
        <div style="margin-left: -135px;margin-bottom: 130px">
          <span style="font-size: 24px">教师重置密码</span>
        </div>
        <n-form ref="formRef" :model="formValue" :rules="rules" class="mt-20 flex flex-col px-15">
          <n-form-item label="账号">
            {{ formValue.account }}
          </n-form-item>
          <n-form-item label="密码" path="password">
            <n-input
                v-model:value="formValue.password"
                placeholder="请输入新密码"
                type="password"
            ></n-input>
          </n-form-item>
          <n-form-item label="重复密码" path="rePassword">
            <n-input
                v-model:value="formValue.rePassword"
                placeholder="请输入相同密码"
                type="password"
            ></n-input>
          </n-form-item>
          <n-form-item>
            <n-button type="primary" @click.prevent="submitForm">确认</n-button>
          </n-form-item>
        </n-form>
      </div>
    </div>
  </CommonPage>
</template>

<script setup>
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import api from '@/api/admin'
import { confirmPasswordRule, strictPasswordRule } from '@/utils/validator'
import sha256 from 'crypto-js/sha256';
import { generateRandomString } from '@/utils';

const route = useRoute()
const router = useRouter()
const { account } = route.query
// 是否通过验证
if (history.state.canAccessResetPassword !== 'true' || !account) {
  router.push({ name: 'AdminRePwInfo' })
}

const defaultFormValue = {
  account: account,
  password: '',
  rePassword: '',
}
const formRef = ref(null)
const formValue = ref({ ...defaultFormValue })

const rules = ref({
  password: strictPasswordRule(),
  rePassword: confirmPasswordRule(formValue, 'password'),
})

const submitForm = async (e) => {
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      try {
        await api.updatePasswordByAccount({
          account: formValue.value.account,

          password: sha256(formValue.value.password.trim()).toString(),
          sessionId: generateRandomString(64)+formValue.value.password.trim(), //应付检查的无用字段

        })
        formValue.value = { ...defaultFormValue }
        $message.success('重置密码成功')
        await router.push({name: 'AdminLogin'})
      } catch (err) {
        $message.error(err.message)
      }
    } else {
      $message.error('表单验证失败')
      console.log('errors', errors)
    }
  })
}
</script>
